package com.doyutu.seed.config.shiro;

import com.doyutu.seed.entity.enums.ResultCodeEnum;
import com.doyutu.seed.entity.result.Result;
import com.doyutu.seed.utils.GsonUtil;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.MediaType;

/**
 * @author DoyuTu
 * @version 0.0.1
 * spring-boot-project-seed
 */
@Slf4j
public class PathMatchesFilter extends PathMatchingFilter {

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        //获取到当前用户
        Subject currentUser = SecurityUtils.getSubject();
        String ends = req.getRequestURI().substring(req.getRequestURI().lastIndexOf("/"));
        System.out.println("地址url拦截" + ends);
        if (currentUser.isAuthenticated()) {
            return true;
        }
   /*     if(currentUser.isPermitted(ends)){
            return true;
        }*/
        Result result = new Result();
        result.setMessage("会话失效,请重新登陆!");
        result.setCode(ResultCodeEnum.FAIL);
        PrintWriter out = null;
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            out = response.getWriter();
            out.write(GsonUtil.toJson(result));
        } catch (IOException e1) {
            log.error(e1.getMessage(), e1);
        } finally {
            IOUtils.closeQuietly(out);
        }
        return false;
    }
}
